import React, {Component} from 'react';
import {Table, Row, Col, Button, Form, Select, Input, Modal, DatePicker, Switch, message} from 'antd';
import "./index.less";
import moment from 'moment'
import {  getDicByTyp,  getDicByType, queryMerchandise, getMerchandise} from "@/api/api";
import {Link} from "react-router-dom";
const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {confirm} = Modal;
class goodAdminList extends Component {
    constructor(props) {
        super(props);
        this.autoSwitch = this.autoSwitch.bind(this);
        this.getTable = this.getTable.bind(this);
        this.state = {
            columns: [
                {title: '展示名称', dataIndex: 'name', key: 'name'},
                {title: '产品名称', dataIndex: 'productName', key: 'productName'},
                {
                    title: '是否上架',
                    key: 'status',
                    width: '200px',
                    render: (text, row, index) => {
                        return (
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={row.status == '2'} defaultChecked={row.status == '2'}
                                    onClick={(checked => this.autoSwitch(checked, 'status', row,index))}/>)
                    }
                },
                {
                    title: '是否可订购',
                    key: 'isOrder',
                    width: '200px',
                    render: (text, row, index) => (
                        <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked={row.isOrder == '1'}
                                onClick={(checked => this.autoSwitch(checked, 'isOrder', row,index))}/>
                    ),
                },
                {title: '销量', dataIndex: 'num', key: 'num'},
                {title: '商品类型（一级）', dataIndex: 'oneTypeName', key: 'oneTypeName'},
                {title: '商品类型（二级）', dataIndex: 'typeName', key: 'typeName'},
                {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime'},
                {title: '创建时间', dataIndex: 'createTime', key: 'createTime'},
                {
                    title: '操作',
                    dataIndex: 'operation',
                    key: 'operation',
                    width: '230px',
                    render: (text, row) => (
                        <Row gutter={16}>
                            <Col className="gutter-row" span={8}>
                                <Button type="primary" ><Link to= {{ pathname : '/goodEdit' , query : { id :`${row.id}` }}}>编辑</Link></Button>
                            </Col>
                            <Col className="gutter-row" span={8}>
                                <Button type="primary" disabled={row.status !== '3'}>
                                    删除
                                </Button>
                            </Col>
                        </Row>),
                },
            ],
            dataSource: [],
            pagination: {
                page: 1,
                limit: 10,
                name: '',
                type: '',
                status: '',
                isOrder: ''
            },
            loading: false,
            selectedRowKeys: [],
            getStatusArr: [],
            count: 0,
            oneTypeList: []
        };
    }

    componentDidMount() {
        this.getTable(this.state.pagination)
        this.getDicByTyp()

        this.getDicByTypeList({level: 2})
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    getDicByTypeList(params) {
        getDicByType(params).then((res) => {
            if (res.code === 0) {
                this.setState({
                    oneTypeList: res.data
                })
                this.state.oneTypeList.unshift({
                    name: '全部',
                    id: ''
                })
            }
        })
    }

    getTable(params) {
        this.setState({loading: true});
        queryMerchandise(params).then(res => {
            const pagination = {...this.state.pagination};
            pagination.total = res.count;
            if (res.code == 0) {
                if (res.data == '获取失败') {
                    this.setState({
                        loading: false,
                        dataSource: [],
                        pagination,
                        count: 0
                    });
                } else {
                    this.setState({
                        loading: false,
                        dataSource: res.data,
                        pagination,
                        count: res.count
                    });
                }

            }
        })
    }

    autoSwitch = (checked, type, row, index) => {
        const dataSource=this.state.dataSource
        let params = {}, titleTips = '', successMessage = '', errorMessage = ''
        if (type == 'status') {
            titleTips = '确定修改可上架状态吗？'
            successMessage = '上架状态修改成功'
            errorMessage = '上架状态修改失败'
            if (checked) {
                params.status = '2'
            } else {
                params.status = '3'
            }
            dataSource[index].status= params.status
            row.status= params.status
        } else {
            titleTips = '确定修改可订购架状态吗？'
            successMessage = '订购状态修改成功'
            errorMessage = '订购状态修改失败'
            if (checked) {
                params.isOrder = '2'
            } else {
                params.isOrder = '1'
            }
            dataSource[index].isOrder= params.isOrder
            row.isOrder= params.isOrder
        }
        params.id = row.id
        let that=this
        confirm({
            title: titleTips,
            okText: "确认",
            cancelText: "取消",
            onOk() {
                getMerchandise(params).then(res => {
                    if (res.msg === 'true') {
                        that.setState({
                            dataSource:dataSource
                        })
                        message.success(successMessage);
                        that.getTable(that.state.pagination)
                    } else {
                        message.error(errorMessage);
                    }
                })
            },
            onCancel() {
                that.setState({
                    dataSource:dataSource
                })
                that.getTable(that.state.pagination)
            },
        });
    }

    getDicByTyp() {
        let params = {
            type: 'ORDER_STATUS'
        }
        this.setState({loading: true});
        getDicByTyp(params).then(res => {
            if (res.code == 0) {
                this.setState({
                    getStatusArr: res.data,
                    loading: false
                })
            }
        })
    }
    handleSearch = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            let params = {
                status: values.status || '',
                limit: 10,
                page: 1,
            }
            for (let key in values) {
                if (values[key] != undefined) {
                    params[key] = values[key]
                }
            }
            if (values) {
                this.getTable(params)
            }
        });
    };
    handleReset = () => {
        this.props.form.resetFields();
        this.getTable(this.state.pagination)
    };
    // 切换分页
    handleTableChange = page => {
        console.log(this.state.pagination)
        const pager = {...this.state.pagination};
        pager.page = page;
        delete pager.total;
        this.getTable(pager);
    };
    onShowSizeChange(pageSize,current){
    }
    render() {
        let {getFieldDecorator} = this.props.form;
        const getStatusOption = this.state.oneTypeList.map((item) => <Option value={item.id} key={item.id}>{item.name}</Option>)
        const totals = this.state.count
        const paginationProps = {
            onChange: page => this.handleTableChange(page),
            onShowSizeChange: (current, pageSize) => this.onShowSizeChange(current, pageSize), //  pageSize 变化的回调
            ...this.state.pagination,
            showSizeChanger: true,
            showTotal: () => `共${totals}条`,
        };
        return (
            <div className="site-card-wrapper">
                <div className="shadow-radius">
                    <Form className="search-form" style={{paddingBottom: 0}}>
                        <Row gutter={24}>
                            <Col span={5}>
                                <FormItem label="展示名称">
                                    {getFieldDecorator('name')(
                                        <Input placeholder="请输入展示名称"/>
                                    )}

                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="商品类型">
                                    {getFieldDecorator('type')(
                                        <Select placeholder="请选择">
                                            {getStatusOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="更新日期">
                                    <RangePicker ranges={{
                                        Today: [moment(), moment()],
                                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                                    }}
                                    />
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="上架状态">
                                    {getFieldDecorator('status')(
                                        <Select placeholder="请选择">
                                            <Option value="">全部</Option>
                                            <Option value={"2"}>已上架</Option>
                                            <Option value={"3"}>未上架</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="订购状态">
                                    {getFieldDecorator('isOrder')(
                                        <Select placeholder="请选择">
                                            <Option value="">全部</Option>
                                            <Option value={"1"}>是</Option>
                                            <Option value={"0"}>否</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col span={2} style={{marginRight: '10px', display: 'flex'}} className="serarch-btns">
                                <FormItem>
                                    <Button icon="search" type="primary" htmlType="submit" className={'btn'}
                                            onClick={this.handleSearch}>
                                        查询
                                    </Button>
                                </FormItem>
                                <FormItem>
                                    <Button className={'btn'} onClick={this.handleReset}>
                                        重置
                                    </Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <Table bordered columns={this.state.columns} dataSource={this.state.dataSource}
                           rowKey={record => record.id}
                           loading={this.state.loading} pagination={paginationProps}/>
                </div>
            </div>
        );
    }
}

export default Form.create()(goodAdminList);
